﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
using InTheHand.Net;

namespace Cockcrow
{
    public partial class ChatMainForm : Form
    {
//초기화 , 버전정보 , 정보
        private BluetoothClient BTC;
        private BluetoothAddress address;
        private Guid service = BluetoothService.SerialPort;
        public static Guid TEXTSERVICE = new Guid("{63236351-8712-4052-8A8E-A94C3ABF2B7D}");
        private Thread thread;
        private bool run = true;
        private BluetoothListener BTL;
        NetworkStream peer;
        public ChatMainForm() 
        { 
            InitializeComponent(); 
            ChatWindow.Text = CockcrowVer();
            /*if (!BluetoothRadio.IsSupported)
            {
                ChatWindow.Text += Environment.NewLine + "No Bluetooth Adapter found!!!";
            }
            else
            {
                if (BluetoothRadio.PrimaryRadio.Mode == RadioMode.PowerOff)
                    BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
                // Create and start a thread, listening for an incoming text message
                thread = new Thread(new ThreadStart(runThread));
                thread.Start();
            }*/
        }   // 초기화인듯 ㅇㅂㅇ; 버전관리

        private void runThread()
        {
            try
            {
                run = true;
                BTL = new BluetoothListener(TEXTSERVICE);
                BTL.Start();
                while (run)
                {
                    BluetoothClient btc = BTL.AcceptBluetoothClient();
                    StreamReader sr = new StreamReader(btc.GetStream());
                    ReceiveTextFunction(sr.ReadToEnd());
                    sr.Close();
                }
            }
            catch { }
        }

        private static String CockcrowVer() { return "Cockcrow ver 090518-16"; }            //중요한 버전!!
        private void AppInformation()                                                       //더 중요한 프로그램 정보!!
        {
            PrintChatFunction(Environment.NewLine + CockcrowVer()
                              + Environment.NewLine + "발코딩의 달인!!"
                              + Environment.NewLine + "개념 + 생각은 저 하늘의 별이 되고"
                              + Environment.NewLine + "지금 먹고싶은것은 고기!!"
                              + Environment.NewLine + "http://me2day.net/cock"
                              + Environment.NewLine + "plzbtrue@gmail.com");
        }
        private void Thanks2()                                                              //Thanks to
        {
            PrintChatFunction(Environment.NewLine + "Thanks to"
                              + Environment.NewLine + "숙소 : 제주대학교 공대4호관 418강의실"
                              + Environment.NewLine + "전기 : 제주대학교 공대4호관 418강의실"
                              + Environment.NewLine + "담요 : 유고곰, Gardenia, 훈수형"
                              + Environment.NewLine + "갈굼 : DoubleJ군, Gardenia"
                              + Environment.NewLine + "음식약탈 : DoubleJ군");
        }
// 기능 //
        private void NickForm() { InputNick NickForm = new InputNick(this); NickForm.Show(); }
        private void BTForm() { BTConnect BTC = new BTConnect(this); BTC.Show(); }
        private void NickInput(string ChangeNick) { UserID.Text = ChangeNick; }                                 // 대화명 변경
        private string IdText() { return UserID.Text + " : " + sendtext.Text; }                                 //  "id : 내용"
        private void AutoScr() { ChatWindow.Select(ChatWindow.Text.Length, 0); ChatWindow.ScrollToCaret(); }    // 자동스크롤 기능
        private void PrintChatFunction(String message) { ChatWindow.Text += Environment.NewLine + message; }
        private static void ClearTextBox(TextBox window) { window.Text=""; }
        public void SetBlutoothClient(BluetoothAddress address, BluetoothClient bluetoothClient) 
        { 
            this.address = address;
            this.BTC = bluetoothClient;
        } //블루투스 주소 받아오기(BTConnect 폼에서)
        private void SendTextFunction()
        {
            if (!string.IsNullOrEmpty(sendtext.Text))
            {
                PrintChatFunction(IdText());
                ClearTextBox(sendtext);
                /*if(BTC.Connected)
                {
                    BTC = new BluetoothClient();
                    BTC.Connect(address, TEXTSERVICE);
                    StreamWriter sw = new StreamWriter(BTC.GetStream());
                    sw.WriteLine(message);
                    sw.Close();
                }*/
            }
        }
        private void ReceiveTextFunction(String message) { PrintChatFunction(message); }
        private void SaveFile()                                                             // 파일 저장기능
        {
            SaveFileDialog SaveFileDlg = new SaveFileDialog();                              // API 호출
            SaveFileDlg.Filter = "텍스트 파일(*.txt) | *.txt| 모든 파일(*.*) | *.*";        // 필터
            SaveFileDlg.FilterIndex = 1;                                                    // 기본필터
            DialogResult ret = SaveFileDlg.ShowDialog();
            if (ret == DialogResult.OK) 
            {
                StreamWriter Output = new StreamWriter(new FileStream(SaveFileDlg.FileName, FileMode.Create));
                Output.Write(this.ChatWindow.Text);
                Output.Close();
            }
        }
        public void NickChange(string nick)
        {
                PrintChatFunction(UserID.Text + " 님이 " + nick + " (으)로 대화명을 변경했습니다"); NickInput(nick);
        }
        public void ConnectBluetooth()
        {
            if (BTC.Connected == false)
            {
                //선택한 디바이스 주소와 연결하려는 서비스를 기반으로 접속
                BTC.Connect(new BluetoothEndPoint(address, service));
                if (BTC.Connected == true)
                {
                    //NetworkStream 을 GetStream() 과 연결함으로써 시리얼포트에서 데이터를 읽어온다. 
                    peer = this.BTC.GetStream(); //Receive Thread 시작
                    Thread th = new Thread(new ThreadStart(Receive));
                    th.Start();
                }
            }
        }
        public void Receive() { int data = peer.ReadByte(); }                               //데이터를 1 바이트씩 읽어온다(블루투스)
// 이벤트가 일어났을때 동작//
        private void KeyEvent(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == System.Windows.Forms.Keys.Enter)) { SendTextFunction(); }
        }
        private void sendbuttonClick(object sender, EventArgs e)        
        {
            if (!string.IsNullOrEmpty(sendtext.Text)) { SendTextFunction(); }
        }
        private void ClearClick(object sender, EventArgs e)             { ClearTextBox(ChatWindow); }       // 지우기 클릭
        private void SaveClick(object sender, EventArgs e)              { SaveFile(); }                     // 저장   클릭
        private void InformationClick(object sender, EventArgs e)       { AppInformation(); }               // Cock   클릭
        private void Thanks(object sender, EventArgs e)                 { Thanks2(); }                      // Thanks to
        private void appendbuttonClick(object sender, EventArgs e)      { Application.Exit(); }             // 종료   클릭
        private void NickChange(object sender, EventArgs e)             { NickForm(); }                     // 대화명 바꾸기
        private void ConnectBTClick(object sender, EventArgs e)         { BTForm(); }                       // 블루투스 연결
    }
}